package com.example.test_flutter.channel

import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.Window
import androidx.appcompat.app.AppCompatActivity
import com.atom.module.logger.Logger
import com.example.test_flutter.BuildConfig
import com.example.test_flutter.R
import io.flutter.embedding.android.FlutterFragment
import io.flutter.plugin.common.*

class BasicMessageChannelActivity : AppCompatActivity() {

    lateinit var flutterFragment: FlutterFragment

    override fun onCreate(savedInstanceState: Bundle?) {
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // 跳转到flutter
        val createDefault = FlutterFragment.createDefault()
        val beginTransaction = supportFragmentManager.beginTransaction()
        beginTransaction.add(R.id.fragmentLayout, createDefault)
        beginTransaction.commit()
        flutterFragment = createDefault
    }

    val Method_Channel = "com.example.flutter_test_call/methodChannel"


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
            flutterFragment.flutterEngine?.apply {
                //1.创建android端的BasicMessageChannel
                val basicMethodChannel =
                    BasicMessageChannel(this.dartExecutor, Method_Channel, StringCodec.INSTANCE)
                //2.向Flutter端发送消息
                basicMethodChannel.send("Hello, this is BasicMethodChannel Send msg!") { replyString ->
                    Log.i("test", "收到了Flutter端发来的回复：$replyString")
                }
            }
        }

        if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            flutterFragment.flutterEngine?.apply {
                //1.创建android端的BasicMessageChannel
                val basicMethodChannel =
                    BasicMessageChannel(
                        this.dartExecutor,
                        Method_Channel,
                        JSONMessageCodec.INSTANCE
                    )
                basicMethodChannel.setMessageHandler { message, reply ->
                    Logger.e(message)
                    reply.reply(" 我是 android native")
                }
            }
        }
        return super.onKeyDown(keyCode, event)
    }

}